package com.example.moscii_usart;

import ioio.lib.api.DigitalOutput;
import ioio.lib.api.Uart;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.bool;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

@SuppressLint("ResourceAsColor")
public class MainActivity extends IOIOActivity implements OnInitListener {
	//TTS object
    private TextToSpeech myTTS;
        //status check code
    private int MY_DATA_CHECK_CODE = 0;
    
	private TextView textView_;
	private	ToggleButton toggleButton_;
	private ScrollView sv;

	private InputStream in_;
	int success = 0;
	
	public String txt = "";
	
	public JSONObject json;
	
	public Handler handler1 = new Handler();
    public Handler handler2 = new Handler();
    public Handler handler3 = new Handler();
    
    boolean task_1 = false;
    
    
    public String formServer = "";
    
    public Runnable task1 = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(task_1){
				if(!formServer.equals("ERROR")){
					
					//speakWords("hello     " + formServer.toString().toLowerCase());
					try {
						json = new JSONObject(formServer);
						if(json.getString("Name").equals("KRITSANA")){
							sv.setBackgroundColor(Color.parseColor("#008000"));
							speakWords("hello "+json.getString("Name").toString().toLowerCase());
							setText(json.getString("Name") + "\n" + "Pass");
							Log.i("Name",json.getString("Name"));
						}
						else{
							sv.setBackgroundColor(Color.parseColor("#FF0000"));
							setText(json.getString("Name")+ " Fail");
							//speakWords("fail");
							speakWords("please contact ");
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					task_1 = false;
				}
				else{
					sv.setBackgroundColor(Color.parseColor("#FF0000"));
					task_1 = false;
				}
				
			}
			
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    
	 // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        
        //check for TTS data
        Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);

	    textView_ = (TextView) findViewById(R.id.textView1);
	    toggleButton_ = (ToggleButton) findViewById(R.id.toggleButton1);
	    sv = (ScrollView) findViewById(R.id.BG);
	    
	    enableUi(false);
	}

	@SuppressLint("ResourceAsColor")
	class Looper extends BaseIOIOLooper {
	    private DigitalOutput led_;

	    private Uart uart_;
	    private OutputStream out_;
	    int counter = 0;
	    int test = 0;
	    Thread readThread = new readDataThread();// creates the read thread

	    @Override
	    public void setup() throws ConnectionLostException {
	        try {
	            led_ = ioio_.openDigitalOutput(0, true);	                        
	            
	            uart_ = ioio_.openUart(40, 3, 9600, Uart.Parity.NONE, Uart.StopBits.ONE);
	            out_ = uart_.getOutputStream();
	            in_ = uart_.getInputStream();

	            readThread.start();// Starts the thread

	            setText("in setup");
	            enableUi(true);
	        } catch (ConnectionLostException e) {
	            enableUi(false);
	            throw e;
	        }
	    }
	    

	    @Override
	    public void loop() throws ConnectionLostException {
	        try {

	            if (success == 5) {
	                readThread.interrupt();// Ends the thread
	                setText("Successful transmission\n" + txt);	                
	                
	                String url = "http://192.168.0.46/Driving/Details";
	            	
	        		List<NameValuePair> params = new ArrayList<NameValuePair>();
	                params.add(new BasicNameValuePair("data", txt));

	                
	            	String resultServer  = getHttpPost(url,params);
	            	//result.setText(resultServer);
	            	
	            	setText(resultServer);
	            	
	            	formServer = resultServer;
	            	
	            	task_1 = true;
	            	handler1.postDelayed(task1, 10);
	            	
	                
	                Thread.sleep(10);
	                txt = "";
	                success = 0;
	            }
	            
	            

	            led_.write(toggleButton_.isChecked());

	        } catch (InterruptedException e) {
	            ioio_.disconnect();
	        } catch (ConnectionLostException e) {
	            enableUi(false);
	            throw e;
	        }
	    }
	}

	@Override
	protected IOIOLooper createIOIOLooper() {
	    return new Looper();
	}

	private void enableUi(final boolean enable) {
	    runOnUiThread(new Runnable() {
	        @Override
	        public void run() {
	            toggleButton_.setEnabled(enable);
	        }
	    });
	}

	private void setText(final String str) {
	    runOnUiThread(new Runnable() {
	        @Override
	        public void run() {
	            textView_.setText(str);
	        }
	    });
	}

	public class readDataThread extends Thread {
	    public void run() {
	        while (true) {
	            try {
	                int i = in_.read();
	                String aString = Integer.toString(i);
	                txt += (char)i+"";
	                
	                    if (i == 10) {
	                        success = 5;
	                        setText("Read in successfully " + txt);
	                        Thread.sleep(10);
	                    } else {
	                        success = 0;
	                        setText(txt);
	                        Thread.sleep(10);
	                    }

	            } catch (InterruptedException ex) {
	                Thread.currentThread().interrupt(); // very important
	                //break;
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        //System.out.println("Shutting down thread");
	    }
	    
	}
	
	public String getHttpPost(String url,List<NameValuePair> params) {
		StringBuilder str = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		
		Log.i("Params", params.toString());
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) { // Status OK
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
			} else {
				Log.e("Log", "Failed to download result..");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}
	
   
   //speak the user text
   private void speakWords(String speech) {

           //speak straight away
           myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
   }
    
       //act on result of TTS data check
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
       if (requestCode == MY_DATA_CHECK_CODE) {
           if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
               //the user has the necessary data - create the TTS
           myTTS = new TextToSpeech(this, this);
           }
           else {
                   //no data - install it now
               Intent installTTSIntent = new Intent();
               installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
               startActivity(installTTSIntent);
           }
       }
   }

       //setup TTS
   public void onInit(int initStatus) {
    
           //check for successful instantiation
       if (initStatus == TextToSpeech.SUCCESS) {
           if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
               myTTS.setLanguage(Locale.US);
       }
       else if (initStatus == TextToSpeech.ERROR) {
           Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
       }
   }
}